﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using PMPUtils.Form;
using PMPUtils.Maintenance;
using PMPUtils.Resources;

namespace PMP.Maintenance
{
    public partial class UserMaintenance : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FormUtil.AuthenticateLead(Session, Response);
        }

        private bool CheckRequiredFields()
        {
            if (txtUserName.Text.Trim().Equals(String.Empty) ||
                txtEmail.Text.Trim().Equals(String.Empty) ||
                ddlManagers.SelectedIndex == -1 ||
                ddlTeams.SelectedIndex == -1)
            {
                return false;
            }

            return true;
        }

        private void CleanUp()
        {
            txtUserName.Text = String.Empty;
            txtEmail.Text = String.Empty;
            ddlTeams.SelectedIndex = -1;
            ddlManagers.SelectedIndex = -1;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            // Check required fields
            if (!CheckRequiredFields())
            {
                Messenger.Show(Response, "Please fill required fields then proceed!");
                return;
            }

            // Derive all values
            String userName = txtUserName.Text.Trim();
            String email = txtEmail.Text.Trim();
            String team = ddlTeams.SelectedValue.Trim();
            String manager = ddlManagers.SelectedValue.Trim();

            // Validate existance
            try
            {
                if (UserMaintain.IsUserAlreadyExist(userName))
                {
                    Messenger.Show(Response, "The user name already exists!");
                    return;
                }
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            // Add user
            try
            {
                UserMaintain.AddNewUser(userName, email, team, manager);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            GridView1.DataBind();
            CleanUp();

            Messenger.Show(Response, "User added successfully!");
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            CleanUp();
        }
    }
}
